//
//  NSImageViewExtension.swift
//  JKTools
//
//  Created by 姜奎 on 2024/4/23.
//

import Cocoa

extension NSImageView {
    func addTrackingArea() {
        let track = NSTrackingArea(rect: self.bounds,options: [.mouseEnteredAndExited, .activeInKeyWindow], owner: self)
        addTrackingArea(track)
        self.isEditable = true
    }
    
    open override func mouseEntered(with event: NSEvent) {
        NSCursor.openHand.set()
    }
    
    open override func mouseExited(with event: NSEvent) {
        NSCursor.arrow.set()
    }
    
    open override func draggingEntered(_ sender: any NSDraggingInfo) -> NSDragOperation {
        return .copy
    }
    
    open override func prepareForDragOperation(_ sender: any NSDraggingInfo) -> Bool {
        return true
    }
    
    open override func performDragOperation(_ sender: any NSDraggingInfo) -> Bool {
        if let image = NSImage(pasteboard: sender.draggingPasteboard) {
            debugPrint("二维码-png")
            self.image = image
            return true
        }
        
        if let pasteboard = sender.draggingPasteboard.propertyList(forType: .fileURL) as? [URL],
           let firstImageURL = pasteboard.first,
           let image = NSImage(contentsOf: firstImageURL) {
            debugPrint("二维码-fileURL")
            self.image = image
            return true
        }
        
        if let pasteboard = sender.draggingPasteboard.propertyList(forType: .URL) as? [URL],
           let firstImageURL = pasteboard.first,
           let image = NSImage(contentsOf: firstImageURL) {
            debugPrint("二维码-URL")
            self.image = image
            return true
        }
        
        return false
    }
}
